package com.atguigu.bigdata.chapter05.sink;

import com.atguigu.bigdata.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author lzc
 * @Date 2022/9/3 9:16
 */
public class Flink06_Sink_Jdbc {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        
        env
            .socketTextStream("hadoop162", 9999)
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                    return new WaterSensor(
                        data[0],
                        Long.valueOf(data[1]),
                        Integer.valueOf(data[2])
                    );
                }
            })
            
            .keyBy(WaterSensor::getId)  // 方法引用
            .sum("vc")
            .addSink(JdbcSink.sink(
                "replace into sensor(id, ts, vc)values(?,?,?)",
                new JdbcStatementBuilder<WaterSensor>() {
                    @Override
                    public void accept(PreparedStatement ps,
                                       WaterSensor ws) throws SQLException {
                        // 给sql中的占位符赋值. 千万不要关闭ps, ps要重用
                        ps.setString(1, ws.getId());
                        ps.setLong(2, ws.getTs());
                        ps.setInt(3, ws.getVc());
                    }
                },
                new JdbcExecutionOptions.Builder()
                    .withBatchIntervalMs(1000)
                    .withBatchSize(1024)
                    .withMaxRetries(3)
                    .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                    .withDriverName("com.mysql.cj.jdbc.Driver")
                    .withUrl("jdbc:mysql://hadoop162:3306/test?useSSL=false")
                    .withUsername("root")
                    .withPassword("aaaaaa")
                    .build()
            ));
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
}
/*
 写出到mysql中
 
 */